const path = require('path');
const { getThemeVariables } = require('ant-design-vue/dist/theme');

const isProd = process.env.NODE_ENV === 'production';

// 判断打包时运行一个查看项目大小的服务
const IS_OPEN_PREVIEW_PLUGIN = process.argv.slice(-1)[0] === '--IS_OPEN_PREVIEW_PLUGIN';

function resolve(dir) {
  return path.join(__dirname, dir);
}

function previewBuild() {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
  return new BundleAnalyzerPlugin();
}

const assetsCDN = {
  externals: {
    axios: 'axios',
    qs: 'Qs',
  },
  css: [],
  js: [
    'https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js',
    'https://cdn.jsdelivr.net/npm/qs/dist/qs.min.js',
  ],
};

function openGzip() {
  const CompressionWebpackPlugin = require('compression-webpack-plugin');
  const compress = new CompressionWebpackPlugin({
    filename: '[path].gz[query]',
    threshold: 10240,
    minRatio: 0.8,
    test: new RegExp('\\.(' + ['js', 'css'].join('|') + ')$'),
    deleteOriginalAssets: false,
  });
  return compress;
}

module.exports = {
  productionSourceMap: false,
  publicPath: '/subapp-vue3/',
  devServer: {
    hot: false,
    disableHostCheck: true,
    port: 5001,
    open: false,
    overlay: {
      warnings: false,
      errors: true,
    },
    proxy: {
      '/api': {
        target: process.env.VUE_APP_REQUEST_BASE_URL,
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/api': '',
        },
      },
    },
    // 支持跨域
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
  },
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'less',
      patterns: [resolve('src/assets/styles/base/variables.less')],
    },
  },
  css: {
    // 是否分离css true:分离css，会造成css无法热更新，false：会把css打包进js中，js一更新css自然更新
    extract: process.env.NODE_ENV !== 'development',
    sourceMap: false,
    loaderOptions: {
      less: {
        lessOptions: {
          modifyVars: {
            ...getThemeVariables(),
          },
          javascriptEnabled: true,
        },
      },
    },
  },
  configureWebpack() {
    const config = {
      plugins: [openGzip()],
    };
    if (IS_OPEN_PREVIEW_PLUGIN) {
      config.plugins.push(previewBuild());
    }
    if (isProd) {
      config.externals = assetsCDN.externals;
    }
    return config;
  },
  chainWebpack(config) {
    if (isProd) {
      config.plugin('html').tap(args => {
        args[0].cdn = assetsCDN;
        return args;
      });
    }
    if (isProd) {
      config.optimization.splitChunks({
        chunks: 'all',
        maxInitialRequests: Infinity,
        minSize: 300000, // 依赖包超过300000bit将被单独打包
        automaticNameDelimiter: '-',
        cacheGroups: {
          vendor: {
            test: /[\\/]node_modules[\\/]/,
            name(module) {
              const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
              return `chunk.${packageName.replace('@', '')}`;
            },
            priority: 10,
          },
        },
      });
    }
    // 绕开编译器在处理sfc时将webcomponent组件理解为vue组件
    config.module
      .rule('vue')
      .use('vue-loader')
      .tap(options => {
        options.compilerOptions = {
          ...(options.compilerOptions || {}),
          isCustomElement: tag => /^micro-app/.test(tag),
        };
        return options;
      });
  },
};
